package com.aplana.ccsd.service;

import info.magnolia.cms.core.MgnlNodeType;
import info.magnolia.cms.util.ContentUtil;
import info.magnolia.jcr.util.NodeUtil;
import info.magnolia.jcr.util.PropertyUtil;
import info.magnolia.module.blossom.dialog.TabBuilder;
import info.magnolia.module.templatingkit.dam.Asset;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.jcr.Node;
import javax.jcr.RepositoryException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aplana.ccsd.enums.TabNumber;
import com.aplana.ccsd.model.Project;
import com.aplana.ccsd.model.ProjectOverview;
import com.aplana.ccsd.util.DialogUtils;
import com.aplana.ccsd.util.JcrNodeUtils;

@SuppressWarnings("deprecation")
@Service
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	private TemplatingService templatingService;

	@Override
	public Project getProject(Node projectPage) throws RepositoryException {
		String title = PropertyUtil.getString(projectPage, "title");

		Project project = new Project(title, JcrNodeUtils.getURL(projectPage));

		Asset image = templatingService.getNodePropertyAsImage(projectPage,
				"image");
		String opinion = templatingService.getNodePropertyAsHtml(projectPage,
				"opinion");
		String customerDescription = templatingService.getNodePropertyAsHtml(
				projectPage, "customerDescription");
		String result = templatingService.getNodePropertyAsHtml(projectPage,
				"result");
		String situation = templatingService.getNodePropertyAsHtml(projectPage,
				"situation");
		String solution = templatingService.getNodePropertyAsHtml(projectPage,
				"solution");
		String summary = templatingService.getNodePropertyAsHtml(projectPage,
				"summary");

		project.setImage(image);
		project.setOpinion(opinion);
		project.setCustomerDescription(customerDescription);
		project.setResult(result);
		project.setSituation(situation);
		project.setSolution(solution);
		project.setSummary(summary);
		
		project.setTechnologyTags(templatingService.getNodePropertyAsTags(projectPage, "projectTechnology"));
		project.setIndustryTags(templatingService.getNodePropertyAsTags(projectPage, "projectIndustry"));
		
		return project;
	}

	@Override
	public void addRandomProjectOverviewDialogControls(TabBuilder tabBuilder) {
		tabBuilder.addEdit("title", "Заголовок", "");
		tabBuilder.addEdit("allProjectsLinkTitle", "Наименование ссылки 'Все'",
				"");
		tabBuilder.addLink("projectsLink", "Страница с проектами",
				"Ссылка на страницу содержащую проекты");
	}

	@Override
	public Node getProjectListPage(Node randomProjectComponent)
			throws RepositoryException {
		String nodeLink = PropertyUtil.getString(randomProjectComponent,
				"projectsLink");

		Node articlesPage = randomProjectComponent.getSession().getNode(
				nodeLink);
		return articlesPage;
	}

	@Override
	public List<Project> findProjects(Node projectsParentPage)
			throws RepositoryException {
		Iterable<Node> pages = NodeUtil.getNodes(projectsParentPage,
				MgnlNodeType.NT_PAGE);
		List<Project> results = new ArrayList<Project>();
		for (Node page : pages) {
			if (!ContentUtil.asContent(page).hasMixin(MgnlNodeType.MIX_DELETED)) {
				Project pr = getProject(page);
				results.add(pr);
			}
		}
		return results;
	}

	@Override
	public void addProjectDialogControls(TabBuilder tabBuilder,
			TabNumber tabNumber) throws RepositoryException {
		if (TabNumber.FIFTH.equals(tabNumber)) {
			tabBuilder.addEdit("title", "Заголовок", "");
			DialogUtils.addDamControl(tabBuilder, "image", "Логотип",
					"Логотип проекта");
			templatingService.addTechnologyMultiSelectControl(tabBuilder,
					"projectTechnology", "Технологии", "Технологии проекта");
			templatingService.addIndustryMultiSelectControl(tabBuilder,
					"projectIndustry", "Отрасли", "Отрасли проекта");
		} else {
			tabBuilder.addFckEditor("opinion", "Мнение о проекте", "");
			tabBuilder.addFckEditor("customerDescription",
					"Описание заказчика", "");
			tabBuilder.addFckEditor("situation", "Ситуация", "");
			tabBuilder.addFckEditor("solution", "Решение", "");
			tabBuilder.addFckEditor("result", "Результат", "");
			tabBuilder.addFckEditor("summary", "Резюме проекта", "");
		}

	}

	@Override
	public ProjectOverview getRandomProjectOverview(Node randomProjectComponent)
			throws RepositoryException {
		Node projectListPage = getProjectListPage(randomProjectComponent);
		List<Project> allResults = findProjects(projectListPage);

		if (allResults.isEmpty()) {
			return null;
		}
		// Gausian
		// int randomIndex = (int) Math.round(Math.random()
		// * (double) (allResults.size()-1));
		Random randomGenerator = new Random();
		int randomIndex = randomGenerator.nextInt(allResults.size());
		Project pr = allResults.get(randomIndex);

		String title = PropertyUtil.getString(randomProjectComponent, "title");
		String allProjectsLinkTitle = PropertyUtil.getString(
				randomProjectComponent, "allProjectsLinkTitle");
		ProjectOverview overview = new ProjectOverview(pr,
				JcrNodeUtils.getURL(projectListPage), title,
				allProjectsLinkTitle);
		return overview;
	}

	@Override
	public void addProjectListDialogControls(TabBuilder tabBuilder) {
		tabBuilder.addEdit("title", "Title", "");
		tabBuilder.addLink("projectsLink", "Страница с проектами",
				"Ссылка на страницу с проектами");
	}

}